import os
import req
from bs4 import BeautifulSoup

headers = {
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7", 
    "Accept-Encoding": "gzip, deflate, br, zstd", 
    "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6", 
    "Host": "cn.baozimhcn.com", 
    "Priority": "u=0, i", 
    "Sec-Ch-Ua": "\"Chromium\";v=\"136\", \"Microsoft Edge\";v=\"136\", \"Not.A/Brand\";v=\"99\"", 
    "Sec-Ch-Ua-Mobile": "?0", 
    "Sec-Ch-Ua-Platform": "\"Windows\"", 
    "Sec-Fetch-Dest": "document", 
    "Sec-Fetch-Mode": "navigate", 
    "Sec-Fetch-Site": "none", 
    "Sec-Fetch-User": "?1", 
    "Upgrade-Insecure-Requests": "1", 
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36 Edg/136.0.0.0"
}

def main():
    url = input("输入漫画详情页的网页链接（如：https://cn.baozimhcn.com/comic/XXX-YYY）：")
    url=url.split("/")
    name=url[4]
    url.insert(4,"chapter")
    url = "/".join(url)
    i=0
    print(f"开始下载：{name}")
    while True:
        url_0=url+f"/0_{i}.html"
        rq = req.Req(url_0,headers=headers)
        response = rq.send()
        if response==None:
            print(f"第{i}章未能获取响应。")
        else:
            if len(response) == 0:
                print(f"下载完毕，共{i+1}章")
                break
            #print(len(response))
            soup=BeautifulSoup(response, 'html.parser')
            imgs = soup.find_all('amp-img')
            for img,k in zip(imgs,range(len(imgs))):
                if "scomic" in img['src']:
                    img_url = img['src']
                    print(f"正在下载第{i}章的第{k+1}张图片：{img_url}")
                    rq = req.Req(img_url, headers=headers)
                    response = rq.send()
                    if response != None:
                        if not os.path.exists(f"./downloads/{name}/第{i}章"):
                            os.makedirs(f"./downloads/{name}/第{i}章")
                        with open(f"./downloads/{name}/第{i}章/{k}.jpg", "wb") as f:
                            f.write(response)
                            print(f"第{i}章的第{k+1}张图片下载完成。")
                    else:
                        print(f"第{i}章的第{k+1}张图片下载失败。")
        i += 1

if __name__ == "__main__":
    main()